package com.lazason.wib4android;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import weibo4andriod.Paging;
import weibo4andriod.Weibo;
import weibo4andriod.WeiboException;
import weibo4andriod.http.AccessToken;
import weibo4andriod.http.RequestToken;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.AdapterContextMenuInfo;

import com.lazason.wib4android.AsyncImageLoader.ImageCallback;

public class Wib extends BasicActivity {
	Weibo weibo;
	int since_id;
	int max_id;

	ListView listView;
	MyAdapter adapter;
	private ProgressBar progressBar;
	LinearLayout layout;
	int page = 1;
	boolean isLoading = false;
	TimeLineTask timeLineTask;
	Paging paging;
	boolean firstLoadImage = true;
	AsyncImageLoader asyncImageLoader;
	PopupWindow window;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		layoutResource = android.R.id.list;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.timeline);
		listView = (ListView) findViewById(android.R.id.list);
		if (savedInstanceState != null) {
			int pos = savedInstanceState.getInt("lastItem", 0);
			listView.setSelection(pos);
		}
		paging = new Paging();
		paging.setPage(page);
		Uri uri = this.getIntent().getData();

		asyncImageLoader = new AsyncImageLoader();
		SharedPreferences mySharedPreferences = getSharedPreferences(WIB, mode);
		String token = mySharedPreferences.getString("token", null);
		String tokenSecret = mySharedPreferences.getString("tokenSecret", null);

		String style = mySharedPreferences.getString("style", null);
		if ("night".equals(style)) {
			MyApplication.style = "night";
			listView.setBackgroundResource(R.color.black);
		} else {
			MyApplication.style = "normal";
			listView.setBackgroundResource(R.color.white);
		}
		// List<weibo4andriod.Status> friendsTimeline = null;
		if (token != null && tokenSecret != null) {
			weibo = OAuthConstant.getInstance().getWeibo();
			weibo.setToken(token, tokenSecret);
			adapter = new MyAdapter(this, MyApplication.data,
					R.layout.listitem, new String[] { "profile", "weibo",
							"username", "picture", "retweetedText",
							"retweetedThumbnailPic", "created_at",
							"comment_repost" }, new int[] { R.id.profile,
							R.id.weibo, R.id.username, R.id.picture,
							R.id.retweetedText, R.id.retweetedThumbnailPic,
							R.id.createdTime, R.id.comment_repost }, listView);
			listView.setAdapter(adapter);
		} else {
			try {
				RequestToken requestToken = OAuthConstant.getInstance()
						.getRequestToken();
				AccessToken accessToken = requestToken.getAccessToken(uri
						.getQueryParameter("oauth_verifier"));
				OAuthConstant.getInstance().setAccessToken(accessToken);
				weibo = OAuthConstant.getInstance().getWeibo();
				weibo.setToken(OAuthConstant.getInstance().getToken(),
						OAuthConstant.getInstance().getTokenSecret());

				SharedPreferences.Editor editor = mySharedPreferences.edit();
				editor.putString("token", accessToken.getToken());
				editor.putString("tokenSecret", accessToken.getTokenSecret());
				editor.putString("style", "nomal");
				editor.commit();
				layout = new LinearLayout(this);
				progressBar = new ProgressBar(this);
				// 进度条显示位置
				progressBar.setPadding(0, 0, 15, 0);
				// 把进度条加入到layout中
				layout.addView(progressBar);

				// setContentView(layout);

				// 文本内容
				TextView textView = new TextView(this);
				textView.setText("加载中...");
				textView.setGravity(Gravity.CENTER_VERTICAL);
				layout.addView(textView);
				listView.addHeaderView(layout);
				FirstTimeLineTask ftlt = new FirstTimeLineTask();
				ftlt.execute();
			} catch (WeiboException e) {
				e.printStackTrace();
			}
		}
		listView.setOnScrollListener(new OnScrollListener() {
			int startIndex;
			int endIndex;

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				startIndex = firstVisibleItem;
				endIndex = firstVisibleItem + visibleItemCount;
				if (endIndex >= totalItemCount) {
					endIndex = totalItemCount - 1;
				}
				if (totalItemCount != 0) {
					if (firstVisibleItem + visibleItemCount > (totalItemCount - 20)
							&& page < 1000) {

						if (!isLoading) {

							isLoading = true;
							// 开线程去下载网络数据

							timeLineTask = new TimeLineTask();
							page++;
							timeLineTask.execute(page);
						}

					}

				}

			}

			@Override
			public void onScrollStateChanged(AbsListView paramAbsListView,
					int paramInt) {
				// TODO Auto-generated method stub

			}

		});
		registerForContextMenu(listView);
		listView.setFocusableInTouchMode(true);
		listView.requestFocus();

		Timer timer = new Timer();
		timer.schedule(new initPopupWindow(), 100);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		int lastItem = listView.getLastVisiblePosition();
		outState.putInt("lastItem", lastItem);
		super.onSaveInstanceState(outState);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle("Context Menu");
		menu.add(0, 0, 0, "Forward");
		menu.add(0, 1, 1, "Comments");
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
	}

	@Override
	public boolean onContextItemSelected(MenuItem aItem) {
		AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) aItem
				.getMenuInfo();

		/* Switch on the ID of the item, to get what the user selected. */
		switch (aItem.getItemId()) {
		case 1:
			/* Get the selected item out of the Adapter by its position. */
			Map info = (Map) listView.getAdapter().getItem(menuInfo.position);
			Log.d("WIB", " position " + menuInfo.position);
			Log.d("WIB", " screen_name " + info.get("username"));
			Log.d("WIB", " user id " + info.get("id"));
			Intent intent = new Intent();
			intent.putExtra("id", String.valueOf(info.get("weibo_id")));
			intent.putExtra("username", (String) info.get("username"));
			intent.putExtra("profile", (String) info.get("profile"));
			intent.putExtra("created_at", Util.getCreatedAtString((Date) info
					.get("created_at")));
			intent.putExtra("picture", (String) info.get("picture"));
			intent.putExtra("weibo", (String) info.get("weibo"));
			intent.setClass(this, PostCommentActivity.class);
			startActivity(intent);
			return true; /* true means: “we handled the event”. */
		}
		return false;
	}

	private class FirstTimeLineTask extends
			AsyncTask<Void, Void, List<weibo4andriod.Status>> {

		protected List<weibo4andriod.Status> doInBackground(Void... arg) {
			List<weibo4andriod.Status> friendsTimeline = null;

			try {

				friendsTimeline = weibo.getFriendsTimeline();

			} catch (WeiboException we) {
				we.printStackTrace();

			} catch (Exception e) {
				e.printStackTrace();

			}

			return friendsTimeline;
		}

		protected void onPostExecute(List<weibo4andriod.Status> friendsTimeline) {
			MyApplication.data = new ArrayList<Map<String, Object>>();
			for (weibo4andriod.Status status : friendsTimeline) {
				Log.d("WIB", status.toString());
				Map<String, Object> map = Util.status2Map(status);
				// Map<String, Object> map = new HashMap<String, Object>();
				//
				// map.put("profile", status.getUser().getProfileImageURL()
				// .toString());
				// map.put("weibo", status.getText());
				// map.put("username", status.getUser().getName());
				// map.put("id", status.getUser().getId());
				MyApplication.data.add(map);

			}

			adapter = new MyAdapter(Wib.this, MyApplication.data,
					R.layout.listitem, new String[] { "profile", "weibo",
							"username", "picture", "retweetedText",
							"retweetedThumbnailPic", "created_at",
							"comment_repost" }, new int[] { R.id.profile,
							R.id.weibo, R.id.username, R.id.picture,
							R.id.retweetedText, R.id.retweetedThumbnailPic,
							R.id.createdTime, R.id.comment_repost }, listView);

			listView.setAdapter(adapter);
			listView.removeHeaderView(layout);
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			// listView.addFooterView(layout);
		}

	}

	private class TimeLineTask extends
			AsyncTask<Integer, Void, List<weibo4andriod.Status>> {

		protected List<weibo4andriod.Status> doInBackground(Integer... page) {
			List<weibo4andriod.Status> friendsTimeline = null;
			friendsTimeline = null;
			try {

				System.out.println("page : " + page[0].intValue());
				paging.setPage(page[0]);

				friendsTimeline = weibo.getFriendsTimeline(paging);

			} catch (WeiboException we) {
				we.printStackTrace();

			} catch (Exception e) {
				e.printStackTrace();

			}

			return friendsTimeline;
		}

		protected void onPostExecute(List<weibo4andriod.Status> friendsTimeline) {
			if (friendsTimeline == null) {
				Toast.makeText(getApplicationContext(), "没有更多的微博",
						Toast.LENGTH_SHORT).show();
				isLoading = false;
				return;
			}
			boolean isWifi = MyApplication.isWifi(Wib.this);
			for (weibo4andriod.Status status : friendsTimeline) {
				Map<String, Object> map = Util.status2Map(status);

				MyApplication.data.add(map);

			}

			// listView.removeFooterView(layout);

			adapter.notifyDataSetChanged();
			isLoading = false;

		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			// listView.addFooterView(layout);
		}

	}

	void preLoadOriginalImage(String id, String url) {
		asyncImageLoader.loadDrawable(this, url, id, Thread.NORM_PRIORITY,
				new ImageCallback() {
					public void imageLoaded(Drawable imageDrawable,
							String imageUrl, String id) {

					}
				});
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		if (MyApplication.data != null) {
			adapter = new MyAdapter(this, MyApplication.data,
					R.layout.listitem, new String[] { "profile", "weibo",
							"username", "picture", "retweetedText",
							"retweetedThumbnailPic", "created_at",
							"comment_repost" }, new int[] { R.id.profile,
							R.id.weibo, R.id.username, R.id.picture,
							R.id.retweetedText, R.id.retweetedThumbnailPic,
							R.id.createdTime, R.id.comment_repost }, listView);
			int lastItem = listView.getFirstVisiblePosition();

			listView.setAdapter(adapter);
			listView.setSelection(lastItem);
		}
		// if(window==null){
		// Timer timer = new Timer();
		// timer.schedule(new initPopupWindow(), 100);
		// }
		super.onResume();
	}

	private Handler mHandler = new Handler() {

		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				showPopupWindow();
				break;
			}
		};
	};

	private void showPopupWindow() {
		LayoutInflater lay = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View v = lay.inflate(R.layout.imagebrowser, null);
		ImageView iv = (ImageView) v.findViewById(R.id.originalImage);
		iv.setFocusable(true);
		iv.setClickable(true);
		iv.setTag("visible");
		iv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				// TODO Auto-generated method stub
				// if("visible".equals((String)((ImageView)view).getTag())){
				// ((ImageView)view).setAlpha(125);
				// ((ImageView)view).setTag("invisible");
				// } else {
				// ((ImageView)view).setAlpha(255);
				// ((ImageView)view).setTag("visible");
				// }
				Intent intent = new Intent();
				intent.setClass(Wib.this, Wib.class);
				startActivity(intent);
			}

		});
		iv.setImageResource(R.drawable.icon);
		// iv.setAlpha(20);
		window = new PopupWindow(v, 50, 50);

		window.setFocusable(false);
		window.setTouchable(true);
		window.setOutsideTouchable(true);
		window.update();
		window.showAtLocation(listView, Gravity.BOTTOM, 0, 0);

	}

	private class initPopupWindow extends TimerTask {
		@Override
		public void run() {

			Message message = new Message();
			message.what = 1;
			mHandler.sendMessage(message);

		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		if (window != null) {
			window.dismiss();
		}
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		if (window != null) {
			window.dismiss();
		}
		super.onDestroy();
	}

}
